<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList"
            size="small">
          查询搜索
        </el-button>
        <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch"
            size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="资源名称：">
            <el-input v-model="listQuery.nameKeyword" class="input-width" placeholder="资源名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="资源路径：">
            <el-input v-model="listQuery.urlKeyword" class="input-width" placeholder="资源路径" clearable></el-input>
          </el-form-item>
          <el-form-item label="资源分类：">
            <el-select v-model="listQuery.categoryId" placeholder="全部" clearable class="input-width">
              <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd" style="margin-left: 20px">添加</el-button>
      <el-button size="mini" class="btn-add" @click="handleShowCategory">资源分类</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="resourceTable" :data="list" style="width: 100%;" v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center" prop="id" />
        <el-table-column label="资源名称" align="center" prop="name" />
        <el-table-column label="资源路径" align="center" prop="url" />
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="添加时间" width="160" align="center">
          <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center">
          <template #default="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          v-model:currentPage="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10, 15, 20]"
          :total="total"
      />
    </div>
    <el-dialog :title="isEdit ? '编辑资源' : '添加资源'" v-model="dialogVisible" width="40%">
      <el-form :model="resource" ref="resourceForm" label-width="150px" size="small">
        <el-form-item label="资源名称：">
          <el-input v-model="resource.name" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="资源路径：">
          <el-input v-model="resource.url" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="资源分类：">
          <el-select v-model="resource.categoryId" placeholder="全部" clearable style="width: 250px">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述：">
          <el-input v-model="resource.description" type="textarea" :rows="5" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm" size="small">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { fetchList, createResource, updateResource, deleteResource } from '@/api/resource';
import { listAllCate } from '@/api/resourceCategory';
import { formatDate } from '@/utils/date';

const router = useRouter();
const listQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  nameKeyword: null,
  urlKeyword: null,
  categoryId: null
});
const list = ref([]);
const total = ref(0);
const listLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const resource = reactive({
  id: null,
  name: null,
  url: null,
  categoryId: null,
  description: ''
});
const categoryOptions = ref([]);
const defaultCategoryId = ref(null);

// 获取资源列表
const getList = async () => {
  listLoading.value = true;
  try {
    const response = await fetchList(listQuery);
    list.value = response.data.data.list;
    total.value = response.data.data.total;
  } finally {
    listLoading.value = false;
  }
};

// 获取分类列表
const getCateList = async () => {
  const response = await listAllCate();
  categoryOptions.value = response.data.data.map(cate => ({ label: cate.name, value: cate.id }));
  defaultCategoryId.value = response.data.data[0]?.id;
};

// 重置搜索条件
const handleResetSearch = () => {
  Object.assign(listQuery, {
    pageNum: 1,
    pageSize: 10,
    nameKeyword: null,
    urlKeyword: null,
    categoryId: null
  });
};

// 搜索
const handleSearchList = () => {
  listQuery.pageNum = 1;
  getList();
};

// 分页大小改变
const handleSizeChange = (val) => {
  listQuery.pageNum = 1;
  listQuery.pageSize = val;
  getList();
};

// 当前页改变
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getList();
};

// 添加资源
const handleAdd = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  Object.assign(resource, {
    id: null,
    name: null,
    url: null,
    categoryId: defaultCategoryId.value,
    description: ''
  });
};

// 删除资源
const handleDelete = (index, row) => {
  ElMessageBox.confirm('是否要删除该资源?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteResource(row.id);
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
    await getList();
  });
};

// 编辑资源
const handleUpdate = (index, row) => {
  dialogVisible.value = true;
  isEdit.value = true;
  Object.assign(resource, row);
};

// 确认对话框
const handleDialogConfirm = async () => {
  ElMessageBox.confirm('是否要确认?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (isEdit.value) {
      await updateResource(resource.id, resource);
      ElMessage({
        message: '修改成功！',
        type: 'success'
      });
    } else {
      await createResource(resource);
      ElMessage({
        message: '添加成功！',
        type: 'success'
      });
    }
    dialogVisible.value = false;
    await getList();
  });
};

// 显示资源分类页面
const handleShowCategory = () => {
  router.push({ path: '/employeeManagement/resourceCategory' });
};

onMounted(() => {
  getList();
  getCateList();
});
</script>

<style scoped>
/* Your styles here */
</style>